package com.ww.springboot.boot.cyclic;

import java.util.HashMap;
import java.util.Map;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2024-01-10 17:51
 */
public class Test2 {

    /**
     * 一级缓存
     */
    private static Map<Class, Object> map = new HashMap<>();

    /**
     * 为什么需要二三级缓存呢
     * 1是 bean创建过程中可能会被代理 所以需要一个区分代理工厂类的缓存
     * 2是 区分成品和半成品bean 简化逻辑 同时避免并发
     * @param args
     */

    //如果不加缓存就会导致死循环
    //加缓存 以解决死循环
    public static void main(String[] args) {
        Object bean = createBean(A.class);
        Object bean1 = createBean(B.class);
        System.out.println(bean.getClass());
        System.out.println(bean1.getClass());
    }

    private static Object createBean(Class clazz) {
        System.out.println("创建bean:" + clazz.getName());
        if (clazz.equals(A.class)) {
            return createA();
        } else if (clazz.equals(B.class)) {
            return createB();
        }
        return null;
    }

    private static A createA() {
        A a = new A();
        if (map.get(A.class) != null) {
            return (A) map.get(A.class);
        }
        map.put(A.class,a);
        Object bean = createBean(B.class);
        a.setB((B)bean);
        return a;
    }

    private static B createB() {
        B b = new B();
        if (map.get(B.class) != null) {
            return (B) map.get(B.class);
        }
        map.put(B.class,b);
        Object bean = createBean(A.class);
        b.setA((A)bean);
        return b;
    }
}
